import Taro from '@tarojs/taro'
import Auth from './auth'

//请求封装
async function request (url, data = {}, method = "POST"){
	const state = Taro.$store.getState();
	const header = {};
	//没有url，直接报错
	if ( !url.trim() ) {
		Taro.showModal({
			title: '出错了',
			content: '请求接口地址不能为空！',
			showCancel: false
		})
		return;
	}

	//数据
	data = Object(data, {})
	
	//请求头
	header['x-access-token'] = Auth.getToken();

	Taro.showLoading({title: '加载中'});
	//请求
	let res = await Taro.request({
		url: `${state.app.baseURL}${url}`,
		data,
		header,
		method
	})

	//返回promise
	return new Promise(resolve=>{
		if( res.statusCode === 200 ){
			if(res.data.error === -1){
				Taro.showModal({
					title: '出错了',
					content: res.data.error_reason,
					showCancel: false
				})
			}else{
				if(res.data.code === 1001){
					//未授权
					Taro.showModal({
						title: '警告',
						content: res.data.msg,
						showCancel: false,
						success: async function (res) {
							if (res.confirm) {
								let result = await Auth.appCheckAuth();
								//授权成功
								if( result ){
									let pages = getCurrentPages();
									Taro.redirectTo({
										url:"/"+pages[0].route
									})
								}else{
									//授权失败
									Taro.showToast({
										title : '授权失败' ,
										icon : 'none' ,
										mask : true
									})
								}

								
							} 
						  }
					})
				}
				else if(res.data.code != 1){
					Taro.showToast({
						title : res.data.msg ,
						icon : 'error' ,
						mask : true
					})
				}
				else{
					// console.log(res.data.msg)
					// Taro.showToast({
					// 	title : res.data.msg ,
					// 	icon : 'success' ,
					// 	mask : true
					// })
					Taro.hideLoading();
					resolve(res.data)
				}
				
			}
		}else{
			Taro.showModal({
				title: '出错了',
				content: '服务器繁忙',
				showCancel: false
			})
		}
	})
}

export default request;